package com.steam.splace;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;


import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONObject;


import bo.DirectionsJSONParser;
import bo.ListViewAdapter;
import bo.UserFunctions;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.internal.p;
import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.GoogleMap.OnMapClickListener;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.BitmapDescriptorFactory;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;
import com.google.android.gms.maps.model.PolylineOptions;
import dao.DataAccess;
import entity.Category;
import entity.Comment;
import entity.Message;
import entity.Place;
import entity.Region;

import thread.DoThread;
import thread.DoThreadGet;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.graphics.Point;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.preference.PreferenceManager;
import android.support.v4.app.FragmentActivity;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.SubMenu;
import android.view.TextureView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewConfiguration;
import android.view.ViewTreeObserver;
import android.widget.AdapterView;
import android.widget.AdapterView.AdapterContextMenuInfo;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class FavoriteActivity extends FragmentActivity implements LocationListener{
	private final int place_tag =10;
	GoogleMap googleMap;
	ListView listComment;
	private float x1,x2;
	static final int MIN_DISTANCE = 150;
    private final int getfavorite_tag =9;
    private final int addfavorite_tag =17;
    private final int addVote_tag =18;
    private final int getComment_tag =11;
    private final int addComment_tag =12;
    private final int deleteComment_tag =13;
    private final int report_tag =16;
    private final int deleteFavorite_tag = 20;
    Intent placeIntent;
	float zoomlevel=14;
	Location location ;
	Menu menu;Handler handler;MenuItem menux;
	int uid=-1;
	String provider;
	LocationManager locationmanager;
	int positionOnListView=-1;
	int pid;
	ContextMenu contextMenu;
	Button bt;
	ArrayList<LatLng> markerPoints;
	ProgressDialog progress;
	 double lat=0;double lng=0;
	Button btAddFavorite;
	ArrayList<Message> arr;
	Place currentPlace;
	private ArrayList<Message> array;
	 private ListViewAdapter arrayAdapter;
	 private ListView list;
	 private Button btGui;
	 private Activity currentContext;
	    boolean mSwiping = false;
	    boolean mItemPressed = false;
	    HashMap<Long, Integer> mItemIdTopMap = new HashMap<Long, Integer>();
	    Message fav;
	    private static final int SWIPE_DURATION = 250;
	    private static final int MOVE_DURATION = 150;
	 public void addFavorite(Message favorite) {
	 array.add(0, favorite);
	 arrayAdapter.notifyDataSetChanged();
	 }
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.favorite_activity);
		currentContext=this;
		progress=new ProgressDialog(currentContext);
		progress.setMessage("Please wait");
	    progress.setIndeterminate(true);
	    progress.setCancelable(false);
	    progress.show();   
		placeIntent= new Intent(this, ViewPlaceActivity.class);
		 handler=new Handler(){
			 @Override
			 public void handleMessage(Message msg){
				 //if(msg.what==2){
			ArrayList<Message> arr=(ArrayList<Message> )msg.obj;
			if(progress.isShowing())progress.dismiss();
			if(arr.size()>0){
			list = (ListView) findViewById(R.id.listFavorite);
			 array = new ArrayList<Message>();
			 arrayAdapter = new ListViewAdapter(currentContext, R.layout.listview, array,mTouchListener);
			 list.setAdapter(arrayAdapter);
			 for(int i=0;i<arr.size();i++){
				 array.add(0, arr.get(i));
			 }
			 
			 list.setOnItemClickListener(new OnItemClickListener() {

			        @Override
			        public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
			        	Message fav=(Message) list.getItemAtPosition(arg2);
			        	Marker marker;
			        	googleMap.clear();
			        	marker = googleMap.addMarker(new MarkerOptions()
						.title(fav.getPlaceName()).position(new LatLng(fav.getLatitude(), fav
								.getLongitude())));
			        	CameraUpdate cameraUpdate = CameraUpdateFactory
								.newLatLngZoom(
										new LatLng(fav.getLatitude(),
												fav.getLongitude()),zoomlevel);
						googleMap.animateCamera(cameraUpdate);

			        }
			    });
			 }
			else {
				
				Toast toast=Toast.makeText(currentContext, "Danh sách ưa thích hiện đang trống!!",
						1000);
				toast.setGravity(Gravity.CENTER, 0, 0);
				toast.show();
			}
				 }
			 
		};
		
		SupportMapFragment fm = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.favmap);
		// Getting GoogleMap object from the fragment
		googleMap = fm.getMap();
		googleMap.setMyLocationEnabled(true);
		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);	
		Thread t=new Thread(new Runnable() {
			@Override
			public void run() {
				if(uid!=-1){
				UserFunctions user=new UserFunctions();
				user.setActivity(currentContext);
				ArrayList<Message> arr=user.getFavorite();
				Message msg=handler.obtainMessage(2, arr);
				handler.sendMessage(msg);
				}
			}
		});
		t.start();
}
	
	 public void myClickHandler(View v) 
	    {
		 Message fav=(Message) list.getItemAtPosition(positionOnListView);
		 DoThreadGet deleteFav=new DoThreadGet(FavoriteActivity.this);
			ArrayList paramsFav=new ArrayList();
			paramsFav.add(deleteFavorite_tag);
			paramsFav.add(fav.getPlaceid());
			paramsFav.add(arrayAdapter);
			paramsFav.add(positionOnListView);
			deleteFav.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR, paramsFav);
	    }

	 private View.OnTouchListener mTouchListener = new View.OnTouchListener() {
		 float mDownX;
	        private int mSwipeSlop = -1;
	        
	        @Override
	        public boolean onTouch(final View v, MotionEvent event) {
	            if (mSwipeSlop < 0) {
	                mSwipeSlop = ViewConfiguration.get(FavoriteActivity.this).
	                        getScaledTouchSlop();
	            }
	            switch (event.getAction()) {
	            case MotionEvent.ACTION_DOWN:
	                if (mItemPressed) {
	                    // Multi-item swipes not handled
	                    return false;
	                }
	                mItemPressed = true;
	                mDownX = event.getX();
	                break;
	            case MotionEvent.ACTION_CANCEL:
	                v.setAlpha(1);
	                v.setTranslationX(0);
	                mItemPressed = false;
	                break;
	            case MotionEvent.ACTION_MOVE:
	                {
	                    float x = event.getX() + v.getTranslationX();
	                    float deltaX = x - mDownX;
	                    float deltaXAbs = Math.abs(deltaX);
	                    if (!mSwiping) {
	                        if (deltaXAbs > mSwipeSlop) {
	                        	System.out.println("swipeslop:"+mSwipeSlop);
	                            mSwiping = true;
	                            list.requestDisallowInterceptTouchEvent(true);
	                            //mBackgroundContainer.showBackground(v.getTop(), v.getHeight());
	                        }
	                    }
	                    if (mSwiping) {
	                        v.setTranslationX((x - mDownX));
	                        v.setAlpha(1 - deltaXAbs / v.getWidth());
	                    }
	                }
	                break;
	            case MotionEvent.ACTION_UP:
	                {
	                    // User let go - figure out whether to animate the view out, or back into place
	                	if(!mSwiping){
	                		
	                		Message fav=(Message) list.getItemAtPosition(list.getPositionForView(v));
	    		        	Marker marker;
	    		        	googleMap.clear();
	    		        	marker = googleMap.addMarker(new MarkerOptions()
	    					.title(fav.getPlaceName()).position(new LatLng(fav.getLatitude(), fav
	    							.getLongitude())));
	    		        	CameraUpdate cameraUpdate = CameraUpdateFactory
	    							.newLatLngZoom(
	    									new LatLng(fav.getLatitude(),
	    											fav.getLongitude()),zoomlevel);
	    					googleMap.animateCamera(cameraUpdate);
	                	}
	                    if (mSwiping) {
	                        float x = event.getX() + v.getTranslationX();
	                        float deltaX = x - mDownX;
	                        float deltaXAbs = Math.abs(deltaX);
	                        float fractionCovered;
	                        float endX;
	                        float endAlpha;
	                        final boolean remove;
	                        if (deltaXAbs > v.getWidth() / 4) {
	                            // Greater than a quarter of the width - animate it out
	                            fractionCovered = deltaXAbs / v.getWidth();
	                            endX = deltaX < 0 ? -v.getWidth() : v.getWidth();
	                            endAlpha = 0;
	                            remove = true;
	                        } else {
	                            // Not far enough - animate it back
	                            fractionCovered = 1 - (deltaXAbs / v.getWidth());
	                            endX = 0;
	                            endAlpha = 1;
	                            remove = false;
	                        }
	                        // Animate position and alpha of swiped item
	                        // NOTE: This is a simplified version of swipe behavior, for the
	                        // purposes of this demo about animation. A real version should use
	                        // velocity (via the VelocityTracker class) to send the item off or
	                        // back at an appropriate speed.
	                        long tmp=0;
	                        if(1-fractionCovered<0)
	                        	tmp=0;
	                        else tmp=(long) (1-fractionCovered);
	                        long duration =  (tmp * SWIPE_DURATION);
	                        System.out.println("width:"+v.getWidth());
	                        System.out.println("delta:"+deltaXAbs);
	                        System.out.println();
	                        System.out.println("fraction"+fractionCovered);
	                        System.out.println("Swipe:"+SWIPE_DURATION);
	                        System.out.println("duration:"+duration);
	                       // list.setEnabled(false);
	                        v.animate().setDuration(duration).
	                                alpha(endAlpha).translationX(endX).
	                                withEndAction(new Runnable() {
	                                    @Override
	                                    public void run() {
	                                        // Restore animated values
	                                        v.setAlpha(1);
	                                        v.setTranslationX(0);
	                                        if (remove) {
	                                            animateRemoval(list, v);
	                                        } else {
	                                            //mBackgroundContainer.hideBackground();
	                                            mSwiping = false;
	                                            //list.setEnabled(true);
	                                        }
	                                    }
	                                });
	                    }
	                }
	                mItemPressed = false;
	                break;
	            default: 
	                return false;
	            }
	            return true;
	        }
	 };
	    private void animateRemoval(final ListView listview, View viewToRemove) {
	        int firstVisiblePosition = listview.getFirstVisiblePosition();
	        // Delete the item from the adapter
	        final int position = list.getPositionForView(viewToRemove);
	       fav=(Message) list.getItemAtPosition(list.getPositionForView(viewToRemove));
	        arrayAdapter.remove(arrayAdapter.getItem(position));
	        if(fav!=null){
            new Thread(new Runnable() {
                public void run() {
                   UserFunctions us=new UserFunctions();
                   us.setActivity(currentContext);
                   
                   int i=us.deleteFavorite(fav.getPlaceid());
                   if(i==0){
                	   runOnUiThread(new Runnable() {
                           public void run() {
                           	Toast toast=Toast.makeText(currentContext, "Xóa thành công",
                  				Toast.LENGTH_LONG);
                  				toast.setGravity(Gravity.CENTER, 0, 0);
                  				toast.show();
                           }
                       });    
                   }
                   else {
                	   
                	   runOnUiThread(new Runnable() {
                           public void run() {

                           	Toast toast=Toast.makeText(currentContext, "Vui lòng thử lại",
                  				Toast.LENGTH_LONG);
                  				toast.setGravity(Gravity.CENTER, 0, 0);
                  				toast.show();
                  				array.add(position, fav);
                  				arrayAdapter.notifyDataSetChanged();
                           }
                       });    
                   }
                }
              }).start();}
	        
	    }
	 
    
public int getUID(){
		ArrayList params1 = new ArrayList();
		params1.add(getfavorite_tag);
		DataAccess da = new DataAccess(this);
		int uid = -1;
		try {
			da.open();
			if (da.getUserInUse() != null)
				uid = da.getUserInUse().getId();
			else
				uid = -1;
		} catch (SQLException e) {
			uid = -1;
		} finally {
			da.close();
		}
		return uid;
	}
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		//getMenuInflater().inflate(R.menu.main, menu);

		SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
		uid = prefs.getInt("uid", -1);	
		if(uid!=-1){
			getMenuInflater().inflate(R.menu.main, menu);
		}
		else getMenuInflater().inflate(R.menu.menunologin, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		this.finish();
		if (item.getItemId() == R.id.menuSearch) {
			if (!this.getClass().getSimpleName().equals("SearchActivity")) {

				Intent searchIntent = new Intent(this, SearchActivity.class);
				startActivity(searchIntent);
			}
		} else if (item.getItemId() == R.id.menuProfile) {
			if (!this.getClass().getSimpleName().equals("ProfileActivity")) {
				Intent profileIntent = new Intent(this, ProfileActivity.class);
				startActivity(profileIntent);
			}
		}
		else if(item.getItemId() == R.id.SignOut){
			DataAccess da=new DataAccess(this);
			try {
				da.open();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			da.signOut();
			da.close();
			SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
			Editor prefsEditor = prefs.edit(); 
			prefsEditor.putInt("uid", -1);
			prefsEditor.putString("token", "");
				prefsEditor.commit();
			this.finish();
			Intent loginIntent = new Intent(this, MainActivity.class);
			startActivity(loginIntent);
		}
		else if(item.getItemId() == R.id.menuSignUp){
			if (!this.getClass().getSimpleName().equals("SignUpActivity")) {

				Intent signUpActivity = new Intent(this, SignUpActivity.class);
				startActivity(signUpActivity);
			}
		}
		else if(item.getItemId() == R.id.menuForgot){
			if (!this.getClass().getSimpleName().equals("ForgotPasswordActivity")) {
				Intent forgotPasswordActivity = new Intent(this, ForgotPasswordActivity.class);
				startActivity(forgotPasswordActivity);
			}
		}
		else if(item.getItemId() == R.id.menuAddPlace){
			if (!this.getClass().getSimpleName().equals("AddPlaceActivity")) {
				Intent addPlaceActivity = new Intent(this, AddPlaceActivity.class);
				startActivity(addPlaceActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSignIn){
			if (!this.getClass().getSimpleName().equals("MainActivity")) {
				Intent mainActivity = new Intent(this, MainActivity.class);
				startActivity(mainActivity);
			}
		}
		else if(item.getItemId() == R.id.menuSearchArea){
			if (!this.getClass().getSimpleName().equals("SearchByAreaActivity")) {
				Intent mainActivity = new Intent(this, SearchByAreaActivity.class);
				startActivity(mainActivity);
			}
		}
		else if(item.getItemId() == R.id.menuFavorite){
			if (!this.getClass().getSimpleName().equals("FavoriteActivity")) {

				Intent favoriteActivity = new Intent(this, FavoriteActivity.class);
				startActivity(favoriteActivity);
			}
		}
		return true;
	}
	@Override
	public void onLocationChanged(Location arg0) {
		// Getting latitude of the current location
				location.setLatitude(arg0.getLatitude());
				location.setLongitude(arg0.getLongitude());
				// Getting longitude of the current location
				// Creating a LatLng object for the current location
		
	}
	@Override
	public void onProviderDisabled(String arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onProviderEnabled(String arg0) {
		// TODO Auto-generated method stub
		
	}
	@Override
	public void onStatusChanged(String arg0, int arg1, Bundle arg2) {
		// TODO Auto-generated method stub
		
	}
	
	
	
}
